﻿using ParadoxNotion.Design;
using UnityEngine;
using Yoozoo.Gameplay.Liberty.AI.Utils;

namespace Yoozoo.Gameplay.Liberty.AI.Node
{
    public class FindCarFrontTarget : CarBaseNode
    {
        protected override void OnExecute()
        {
            var pathManager = AIGraphUtils.TrafficManager.PathManager;
            
            Vector3 frontPos = _carEntity.vehicleSetting.FrontPosition;
            Vector3 carForward = _carEntity.forward;

            var pointData = pathManager.GetClosestPathPoints(_data.pathId, frontPos);

            int c = 0;
            while (pointData!=null && 
                   c < 10 && 
                   Vector3.Angle(pointData.position - frontPos,carForward) > 90)
            {
                pointData = 
                    pathManager.GetNextPoint(pointData.pathId, pointData.pointIndex, PathDirection.Forward);
                c++;
            }

            if (pointData!=null)
            {
                _carEntity.data.pathId = pointData.pathId;
                _carEntity.data.pathPointIndex = pointData.pointIndex;
                EndAction(true);
            }
            else
            {
                EndAction(false);
            }
        }
    }
}